import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Modal, Input, message } from 'antd';
import _ from 'lodash';
import './index.less';
import { descriptions } from '../../../task-list/add-task/components/add-task-form/constant';
import {
  IPV4_CIDE_RE,
  IPV6_CIDE_RE,
  IP_INTERVAL_RE,
  IP_RE,
  IP_V6,
  NAME_RE,
  DOMAIN_RE,
  FULL_URL_RE
} from '@util/constants';

const { TextArea } = Input;
const prefixCls = 'white-list-modal';

class WhiteListModal extends Component {
  static defaultState = {
    ips: '',
    remarks: '',
    remarksError: '',
    ipsError: '',
    isEdit: false,
    id: '',
    isCorrectFormat: false
  };
  constructor(props) {
    super(props);
    this.state = {
      ...WhiteListModal.defaultState
    };
  }
  // eslint-disable-next-line
  UNSAFE_componentWillReceiveProps(props) {
    if (props.modalVisible) {
      const { ip = '', remarks = '', _id = '' } = props.rowData;
      const isEdit = !ip;
      this.setState({ ips: ip, remarks, isEdit, id: _id, isCorrectFormat: false, ipsError: '' });
    }
  }

  onClickSubmit = () => {
    const { ips, remarks, id, isEdit, ipsError } = this.state;
    if (!ips) {
      message.error('请填写目标！');
      return;
    }
    if (this.checkRemarks() || ipsError) {
      return;
    }

    const { onClickSubmit } = this.props;
    let body = { ips: _.uniq(ips.split('\n')), remarks: remarks.replace(/\s/g, '') };
    if (isEdit) {
      onClickSubmit('add', body);
    } else {
      body['ip_id'] = id;
      delete body.ips;
      onClickSubmit('edit', body);
    }
  };

  checkRemarks = () => {
    const { remarks } = this.state;
    let remarksError = '';
    if (remarks.length > 32) {
      remarksError = '您输入的内容超过32个字符限制';
    }
    if (!NAME_RE.test(remarks)) {
      remarksError = '您输入的格式有误，仅支持中文、英文、数字、特殊字符 - 、— \\ _ / ：~';
    }
    if (!remarks) {
      remarksError = '';
    }
    this.setState({ remarksError });
    return remarksError;
  };

  onIpChange = e => {
    const value = e.target.value;
    const targets = _.split(value, '\n');
    this.setState({ ips: e.target.value }, this.targetCountSum(value, targets));
  };

  onRemarksChange = e => {
    this.setState({ remarks: e.target.value }, this.checkRemarks);
  };

  targetCountSum = (value, targets) => {
    let ipsError = value.length ? '' : '探测目标不能为空';

    for (let i = 0; i < targets.length; i++) {
      const target = targets[i];
      if (
        !(
          DOMAIN_RE.test(target) ||
          IP_RE.test(target) ||
          IP_V6.test(target) ||
          FULL_URL_RE.test(target) ||
          IPV4_CIDE_RE.test(target) ||
          IPV6_CIDE_RE.test(target) ||
          IP_INTERVAL_RE.test(target, true)
        )
      ) {
        ipsError = '探测目标格式错误';
        break;
      } else if (IPV6_CIDE_RE.test(target)) {
        const prefixLength = target.split('/')[1];

        if (prefixLength < 118) {
          ipsError = '单个IPv6最大支持1024个地址';
          break;
        }
      } else if (IP_INTERVAL_RE.test(target, true)) {
        const targetGroup = target.split('-');
        const startIPArr = targetGroup[0].split('.').map(Number);
        const endIPArr = targetGroup[1].split('.').map(Number);
        if (startIPArr[0] !== endIPArr[0] || endIPArr[1] !== startIPArr[1]) {
          ipsError = '起始IP和末尾IP只允许最后两位不同';
          break;
        }
        const rangeC = endIPArr[2] - startIPArr[2];
        const rangeD = endIPArr[3] - startIPArr[3];
        const ipCount = rangeC * Math.pow(2, 8) + rangeD;
        if (ipCount <= 0) {
          ipsError = '起始IP必须小于末尾IP';
          break;
        }
      }
      ipsError = '';
    }
    this.setState({ ipsError });
  };

  render() {
    const { modalVisible = false, closeModal, confirmLoading } = this.props;
    const { ips, remarks, remarksError, ipsError, isEdit } = this.state;
    return (
      <Modal
        maskClosable={false}
        title={isEdit ? '添加禁扫目标' : '编辑禁扫目标'}
        className={prefixCls}
        visible={modalVisible}
        onOk={this.onClickSubmit}
        onCancel={closeModal}
        confirmLoading={confirmLoading}
        destroyOnClose={true}
      >
        <div className={`${prefixCls}-item remarks`}>
          <div className={`${prefixCls}-item-title`}>备注</div>
          <div className={`${prefixCls}-item-content`}>
            <Input
              placeholder="请输入中文、英文、特殊字符或数字，不超过32个字符"
              value={remarks}
              onChange={this.onRemarksChange}
            />
            {remarksError && <span className={`${prefixCls}-item-error`}>{remarksError}</span>}
          </div>
        </div>
        <div className={`${prefixCls}-item`}>
          <div className={`${prefixCls}-item-title`}>目标</div>
          <div className={`${prefixCls}-item-content`}>
            <TextArea
              rows={9}
              placeholder={descriptions.customIpsPlaceholder}
              value={ips}
              onChange={this.onIpChange}
              disabled={!isEdit}
            />
            {ipsError && <span className={`${prefixCls}-item-error`}>{ipsError}</span>}
          </div>
        </div>
      </Modal>
    );
  }
}

WhiteListModal.propTypes = {
  modalVisible: PropTypes.bool,
  confirmLoading: PropTypes.bool,
  onClickSubmit: PropTypes.func,
  closeModal: PropTypes.func,
  rowData: PropTypes.object
};

export default WhiteListModal;
